﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Kz.Telegram.Bot.Infrastructure.Extensions
{
    public static class EnumExtension
    {
        public static string GetDesc(this Enum obj)
        {
            if (obj == null)
                return string.Empty;

            var type = obj.GetType();
            //获取到:Admin
            var enumName = Enum.GetName(type, obj);
            var field = type.GetField(enumName);
            //获取到:0
            _ = (int)field.GetValue(null);
            var atts = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (atts != null && atts.Length > 0)
            {
                var att = ((DescriptionAttribute[])atts)[0];
                return att.Description;
            }
            return string.Empty;
        }

        /// <summary>
        /// 扩展方法，获得枚举的Description,性能更快
        /// </summary>
        /// <param name="value">枚举值</param>
        /// <param name="nameInstead">当枚举值没有定义DescriptionAttribute，是否使用枚举名代替，默认是使用</param>
        /// <returns>枚举的Description</returns>
        public static string GetFastDesc(this Enum value, bool nameInstead = true)
        {
            Type type = value.GetType();
            string name = Enum.GetName(type, value);
            if (name == null)
            {
                return null;
            }

            FieldInfo field = type.GetField(name);
            DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;

            if (attribute == null && nameInstead == true)
            {
                return name;
            }
            return attribute?.Description;
        }
    }
}
